<?php
namespace Yousheng\DatabaseToolbox\Json2Migration;

class JsonParser {
    /**
     * Path of the JSON schema
     * 
     * @var string
     */
    protected $path;

    /**
     * Create a new JSON Parser instance
     * 
     * @param string $path
     * @return void
     */
    public function __construct(String $path) {
        $this->path = $path;
        if(!file_exists($this->path)) throw new \Exception("JSON Schema file does not exist.");
    }

    /**
     * Parse the JSON file into array
     * 
     * @return array
     */
    public function parse() {
        $json = $this->get();
        $schema = [];
        foreach($json as $table => $columns) {
            $schema[$table] = [];
            foreach($columns as $column => $parameters) {
                $parametersList = explode('|', $parameters);
                $parametersList = array_map(function($parameter) {
                    return explode(':', $parameter);
                }, $parametersList);

                $schema[$table][$column] = $parametersList;
            }
        }
        return $schema;
    }

    /**
     * Load JSON from file
     * 
     * @return array
     */
    public function get() {
        $json = file_get_contents($this->path);
        // 如果是json5格式的，清除注释，暂时手写，后面可以考虑使用 json5::decode 来处理
        if(str_ends_with($this->path,'.json5')){
            $json=$this->clearcomments($json);
        }
        return json_decode($json, true);
    }
    private function clearcomments($content):string{
        $singleCommentRegular="/(\/\/|#).*\n/";                         //单行 或 # 单行
        //$singleCommentRegular2="/\/\*([\s\S]*?)\*\//";                 /* 单行 */
        $multiCommentRegular ="/^\s*\/\*\*?[^!][.\s\t\S\n\r]*?\*\//m";   /** 多行 */
        return preg_replace($multiCommentRegular,"",preg_replace($singleCommentRegular,"",$content));
    }


}